/*
* Create by yz_wy_power on 2018/5/25
*/
/**1.
 * 简单的缓存模块，添加前缀
 * 默认超时时间为60s
 * 默认storage为localStorage
 * isSessionStorage true代表storage为sessionStorage
 */
/**2.
 * 做一个兼容
 * 不支持storage的浏览器使用cookie方式
 */

import Cookies from 'js-cookie'

const PREFIX = 'yzDevR_';
const isSupportStorage = !!window.localStorage;

function isInteger(obj) {
    return typeof obj === 'number' && obj % 1 === 0
}

let storage = {
    set: function set(key, data, timeout, isSessionStorage) {
        let storage = !isSessionStorage ? localStorage : sessionStorage
        let now = Math.round(new Date().getTime() / 1000)
        if (!timeout) {
            timeout = 24 * 60 * 60 * 10
        } else if (!isInteger(timeout)) {
            throw new Error('timeout必须为整数')
        }
        let jsonData = {'data': data, 'timeout': now + timeout}
        try {
            storage.setItem(PREFIX + key, JSON.stringify(jsonData))
        } catch (e) {
            if (e.name === 'QuotaExceededError') {
                console.log('已经超出本地存储限定大小！')
                storage.clear()
                storage.setItem(PREFIX + key, JSON.stringify(jsonData))
            }
        }
    },
    get: function get(key, defaultValue, isSessionStorage) {
        let storage = !isSessionStorage ? localStorage : sessionStorage
        let value = storage.getItem(PREFIX + key)
        if (!value) return defaultValue
        try {
            value = JSON.parse(value)
        } catch (e) {
            console.error('load cache error, return default value')
            return defaultValue
        }

        if (!value.timeout || !value.data) {
            return defaultValue
        }
        let now = Math.round(new Date().getTime() / 1000)
        if (value.timeout < now) {
            this.del(key)
            return defaultValue
        }

        return value.data
    },
    del: function del(key, isSessionStorage) {
        let storage = !isSessionStorage ? localStorage : sessionStorage
        storage.removeItem(PREFIX + key)
    }
};
let cookie = {
    get: function (key, defaultValue) {
        let value = Cookies.get(PREFIX + key);
        if (!defaultValue) {
            defaultValue = undefined
        }
        return value || defaultValue
    },
    set: function (key, data, timeout) {
        if (!timeout) {
            timeout = 24 * 60 * 60 * 10
        } else if (!Number(timeout)) {
            throw new Error('timeout必须为number类型')
        }
        let timeUnitTransform = timeout / (24 * 60 * 60);
        Cookies.set(PREFIX + key, data, {expires: timeUnitTransform})
    },
    del: function (key) {
        Cookies.remove(PREFIX + key)
    }
};
export default {
    get: isSupportStorage ? storage.get : cookie.get,
    del: isSupportStorage ? storage.del : cookie.del,
    set: isSupportStorage ? storage.set : cookie.set
}
